/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-09-03
 * Time: 21:12
 */

/*
 * 实现阻塞队列
 * */
public class MyBlockingQueue {
    private static int[] data = null;
    private volatile int head = 0;//队头
    private volatile int tail = 0;//队尾
    private volatile int size = 0;//个数

    public MyBlockingQueue(int capacity) {
        data = new int[capacity];
    }

    //放入
    public void put(int val) throws InterruptedException {
        //如果队列满了就阻塞
        synchronized (this) {
            //下面全部操作都不是原子的,所以要使用synchronized
            while (size == data.length) {
                //这里使用while的原因:wait也可能被Interrupt唤醒
                this.wait();
            }

            data[tail] = val;
            tail++;
            if (tail >= data.length) {
                tail = 0;
            }
            size++;
            this.notify();//队列不为空了唤醒
        }
    }

    //取出
    public int take() throws InterruptedException {
        int tmp;
        synchronized (this) {
            //下面全部操作都不是原子的,所以要使用synchronized
            while (size == 0) {
                //队列为空,阻塞
                this.wait();
            }
            tmp = data[head];
            if (head >= data.length) {
                head = 0;
            }
            head++;
            size--;
            this.notify();
        }
        return tmp;
    }
}
